<template>
  <view class="xen-material-list">
    <!-- 头部 -->
    <view class="list-header">
      <text class="header-title">选择物料</text>
      <view class="close-btn" @click="handleClose">
        <uni-icons type="close" size="24" color="#fff" />
      </view>
    </view>

    <!-- 筛选区域 -->
    <view class="filter-area">
      <!-- 默认显示的搜索栏 -->
      <view class="search-bar">
        <input
          class="search-input"
          v-model="filterParams.Name"
          placeholder="物料名称"
          @confirm="handleFilterSearch"
        />
        <button class="btn-reset" @click="handleFilterReset">重置</button>
        <button class="btn-search" @click="handleFilterSearch">搜索</button>
        <view class="btn-filter" @click="toggleFilterExpand">
          <uni-icons
            type="settings"
            size="18"
            :color="filterExpanded ? '#7881de' : '#999'"
          />
        </view>
      </view>

      <!-- 展开的筛选条件 -->
      <view v-if="filterExpanded" class="filter-expand">
        <view class="filter-row">
          <view class="filter-item">
            <text class="filter-label">物料编码</text>
            <input
              class="filter-input"
              v-model="filterParams.Code"
              placeholder="请输入物料编码"
              @confirm="handleFilterSearch"
            />
          </view>
        </view>
        <view class="filter-row">
          <view class="filter-item">
            <text class="filter-label">选择状态</text>
            <picker
              class="filter-picker"
              mode="selector"
              :range="stateOptions"
              :value="statePickerIndex"
              @change="handleStateChange"
            >
              <view class="picker-display">
                {{ stateDisplayValue }}
              </view>
            </picker>
          </view>
        </view>
        <view class="filter-row">
          <view class="filter-item">
            <text class="filter-label">ERP物料编码</text>
            <input
              class="filter-input"
              v-model="filterParams.ErpId"
              placeholder="请输入ERP物料编码"
              @confirm="handleFilterSearch"
            />
          </view>
        </view>
        <view class="filter-row">
          <view class="filter-item">
            <text class="filter-label">ERP物料名称</text>
            <input
              class="filter-input"
              v-model="filterParams.ErpName"
              placeholder="请输入ERP物料名称"
              @confirm="handleFilterSearch"
            />
          </view>
        </view>
        <view class="filter-row">
          <view class="filter-item">
            <text class="filter-label">ERP物料型号</text>
            <input
              class="filter-input"
              v-model="filterParams.ErpModel"
              placeholder="请输入ERP物料型号"
              @confirm="handleFilterSearch"
            />
          </view>
        </view>
      </view>
    </view>

    <!-- 物料列表 -->
    <scroll-view
      class="material-list-content"
      scroll-y
      @scrolltolower="loadMore"
    >
      <view
        v-if="loading && materialList.length === 0"
        class="loading-container"
      >
        <uni-icons
          type="spinner-cycle"
          size="32"
          color="#7881de"
          class="loading-icon"
        />
        <text class="loading-text">加载中...</text>
      </view>

      <view v-else-if="materialList.length === 0" class="empty-container">
        <uni-icons type="info" size="48" color="#ccc" />
        <text class="empty-text">暂无物料数据</text>
      </view>

      <view v-else class="material-items">
        <view
          v-for="material in materialList"
          :key="material.ID || ''"
          class="material-card"
        >
          <view class="card-content">
            <!-- 物料名称 -->
            <view class="material-name">{{ material.Name }}</view>

            <!-- 物料信息行 -->
            <view class="info-row">
              <view class="info-item">
                <text class="info-label">分类:</text>
                <text class="info-value">{{
                  material.MaterialGroupName || "-"
                }}</text>
              </view>
              <view class="info-item">
                <text class="info-label">单位:</text>
                <text class="info-value">{{ material.UnitName || "-" }}</text>
              </view>
            </view>

            <view class="info-row">
              <view class="info-item">
                <text class="info-label">状态:</text>
                <text
                  class="state-badge"
                  :class="
                    material.State === '启用'
                      ? 'state-enabled'
                      : 'state-disabled'
                  "
                >
                  {{ material.State }}
                </text>
              </view>
            </view>

            <!-- 详情 -->
            <view v-if="material.Description" class="material-desc">
              <text class="info-label">详情:</text>
              <text class="desc-value">{{ material.Description }}</text>
            </view>
          </view>

          <!-- 操作按钮 -->
          <view class="card-actions">
            <button
              class="select-model-btn"
              @click="handleSelectModel(material)"
            >
              选择型号
            </button>
          </view>
        </view>
      </view>

      <!-- 加载更多提示 -->
      <view v-if="loadingMore" class="loading-more">
        <uni-icons
          type="spinner-cycle"
          size="20"
          color="#999"
          class="loading-icon"
        />
        <text class="loading-text">加载更多...</text>
      </view>

      <view v-if="noMore && materialList.length > 0" class="no-more">
        <text>没有更多数据了</text>
      </view>
    </scroll-view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, watch } from "vue";
import commonApi from "@/api/common";
import type { ISysMaterial, ISysMaterialQuery } from "./type/interface";

interface Props {
  visible?: boolean;
}

interface Emits {
  (e: "select", material: ISysMaterial): void;
  (e: "close"): void;
}

const props = defineProps<Props>();
const emit = defineEmits<Emits>();

// API实例
const api = commonApi();

// 数据状态
const materialList = ref<ISysMaterial[]>([]);
const loading = ref(false);
const loadingMore = ref(false);
const noMore = ref(false);

// 筛选参数
const filterParams = ref<any>({
  Code: "",
  Name: "",
  State: "",
  ErpId: "",
  ErpName: "",
  ErpModel: "",
});

// 筛选展开状态
const filterExpanded = ref(false);

// 状态选择器
const stateOptions = ["选择状态", "启用", "禁用"];
const statePickerIndex = ref(0);
const stateDisplayValue = computed(() => {
  return stateOptions[statePickerIndex.value];
});

// 分页参数
const currentPage = ref(1);
const pageSize = 20;

// 状态选择器变化
const handleStateChange = (e: any) => {
  statePickerIndex.value = e.detail.value;
  // 0=选择状态(空), 1=启用, 2=禁用
  const stateValues = ["", "启用", "禁用"];
  filterParams.value.State = stateValues[e.detail.value];
};

// 加载物料列表
const loadMaterialList = async (isLoadMore = false) => {
  if (isLoadMore) {
    if (noMore.value || loadingMore.value) return;
    loadingMore.value = true;
  } else {
    if (loading.value) return;
    loading.value = true;
    currentPage.value = 1;
    noMore.value = false;
  }

  try {
    const queryParams: ISysMaterialQuery = {
      Page: currentPage.value,
      Limit: pageSize,
      Name: filterParams.value.Name || "",
      Code: filterParams.value.Code || "",
      State: filterParams.value.State || "",
      ErpId: filterParams.value.ErpId || "",
      ErpName: filterParams.value.ErpName || "",
      ErpModel: filterParams.value.ErpModel || "",
    };

    console.log("=== 物料列表查询参数 ===", queryParams);
    const response = await api.GetMaterialList(queryParams);
    console.log("=== 物料列表API响应 ===", response);

    // 注意：API返回的是 Data（大写D），不是 data（小写d）
    if (response && response.Data && Array.isArray(response.Data)) {
      const newData = response.Data;
      console.log("=== 物料列表数据 ===", newData.length, "条", newData);

      if (isLoadMore) {
        materialList.value = [...materialList.value, ...newData];
      } else {
        materialList.value = newData;
      }

      // 判断是否还有更多数据
      if (newData.length < pageSize) {
        noMore.value = true;
      } else {
        currentPage.value++;
      }
    } else {
      console.warn("=== 物料列表数据格式异常 ===", response);
      materialList.value = [];
    }
  } catch (error) {
    console.error("加载物料列表失败:", error);
    uni.showToast({
      title: "加载失败，请重试",
      icon: "none",
    });
  } finally {
    loading.value = false;
    loadingMore.value = false;
  }
};

// 切换筛选展开状态
const toggleFilterExpand = () => {
  filterExpanded.value = !filterExpanded.value;
};

// 筛选搜索
const handleFilterSearch = () => {
  loadMaterialList(false);
};

// 重置筛选
const handleFilterReset = () => {
  filterParams.value = {
    Code: "",
    Name: "",
    State: "",
    ErpId: "",
    ErpName: "",
    ErpModel: "",
  };
  statePickerIndex.value = 0;
  filterExpanded.value = false; // 重置时收起筛选
  loadMaterialList(false);
};

// 加载更多
const loadMore = () => {
  loadMaterialList(true);
};

// 选择型号
const handleSelectModel = (material: ISysMaterial) => {
  emit("select", material);
};

// 关闭
const handleClose = () => {
  emit("close");
};

// 监听visible变化，重新加载数据
watch(
  () => props.visible,
  (newVal) => {
    console.log("=== XenMaterialList visible 变化 ===", newVal);
    if (newVal) {
      // 清空之前的数据和状态
      materialList.value = [];
      currentPage.value = 1;
      noMore.value = false;
      filterParams.value = {
        Code: "",
        Name: "",
        State: "",
        ErpId: "",
        ErpName: "",
        ErpModel: "",
      };
      statePickerIndex.value = 0;
      filterExpanded.value = false; // 重置展开状态
      // 加载数据
      loadMaterialList(false);
    }
  },
  { immediate: true }, // 立即执行一次
);
</script>

<style lang="scss" scoped>
.xen-material-list {
  display: flex;
  flex-direction: column;
  height: 100%;
  background-color: #f5f5f5;

  .list-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 16px 20px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: #ffffff;

    .header-title {
      font-size: 18px;
      font-weight: 600;
    }

    .close-btn {
      padding: 4px;
      cursor: pointer;
    }
  }

  .filter-area {
    background-color: #ffffff;
    border-bottom: 1px solid #e0e0e0;

    .search-bar {
      display: flex;
      align-items: center;
      gap: 8px;
      padding: 12px 16px;

      .search-input {
        flex: 1;
        height: 36px;
        padding: 0 12px;
        font-size: 14px;
        border: 1px solid #e0e0e0;
        border-radius: 6px;
        background-color: #f8f9fa;
      }

      button {
        height: 36px;
        padding: 0 16px;
        font-size: 13px;
        border: none;
        border-radius: 6px;
        cursor: pointer;
      }

      .btn-reset {
        background-color: #f5f5f5;
        color: #666;

        &:active {
          background-color: #e0e0e0;
        }
      }

      .btn-search {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: #ffffff;

        &:active {
          opacity: 0.9;
        }
      }

      .btn-filter {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 36px;
        height: 36px;
        border-radius: 6px;
        background-color: #f5f5f5;
        cursor: pointer;
        transition: all 0.3s ease;

        &:active {
          background-color: #e0e0e0;
        }
      }
    }

    .filter-expand {
      padding: 0 16px 12px;
      border-top: 1px solid #f0f0f0;
      animation: slideDown 0.3s ease;

      .filter-row {
        margin-top: 12px;
      }

      .filter-item {
        .filter-label {
          display: block;
          font-size: 13px;
          color: #666;
          margin-bottom: 8px;
        }

        .filter-input {
          width: 100%;
          height: 36px;
          padding: 0 12px;
          font-size: 14px;
          border: 1px solid #e0e0e0;
          border-radius: 6px;
          background-color: #f8f9fa;
          box-sizing: border-box;
        }

        .filter-picker {
          .picker-display {
            width: 100%;
            height: 36px;
            line-height: 36px;
            padding: 0 12px;
            font-size: 14px;
            border: 1px solid #e0e0e0;
            border-radius: 6px;
            background-color: #f8f9fa;
            color: #666;
            box-sizing: border-box;
          }
        }
      }
    }
  }

  @keyframes slideDown {
    from {
      opacity: 0;
      max-height: 0;
    }
    to {
      opacity: 1;
      max-height: 200px;
    }
  }

  .material-list-content {
    flex: 1;
    height: 0; /* 关键：配合 flex: 1 使用，让 scroll-view 可以正确计算高度 */
    padding: 12px 16px;
    box-sizing: border-box;

    .loading-container,
    .empty-container {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      padding: 60px 20px;
      color: #999;

      .loading-icon {
        animation: rotate 1s linear infinite;
      }

      .loading-text,
      .empty-text {
        margin-top: 12px;
        font-size: 14px;
      }
    }

    .material-items {
      display: flex;
      flex-direction: column;
      gap: 12px;

      .material-card {
        background-color: #ffffff;
        border-radius: 12px;
        overflow: hidden;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);

        .card-content {
          padding: 16px;

          .material-name {
            font-size: 16px;
            font-weight: 600;
            color: #333;
            margin-bottom: 12px;
          }

          .info-row {
            display: flex;
            gap: 20px;
            margin-bottom: 8px;

            .info-item {
              display: flex;
              align-items: center;
              gap: 4px;
              font-size: 13px;

              .info-label {
                color: #666;
              }

              .info-value {
                color: #333;
              }

              .state-badge {
                padding: 2px 8px;
                border-radius: 4px;
                font-size: 12px;

                &.state-enabled {
                  background-color: #e8f5e9;
                  color: #4caf50;
                }

                &.state-disabled {
                  background-color: #ffebee;
                  color: #f44336;
                }
              }
            }
          }

          .material-desc {
            margin-top: 8px;
            padding-top: 8px;
            border-top: 1px solid #f0f0f0;
            font-size: 13px;

            .info-label {
              color: #666;
            }

            .desc-value {
              color: #666;
              margin-left: 4px;
            }
          }
        }

        .card-actions {
          padding: 8px 30px;
          border-top: 1px solid #f0f0f0;
          background-color: #fafafa;

          .select-model-btn {
            width: 100%;
            padding: 2px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: #ffffff;
            font-size: 14px;
            font-weight: 500;
            border: none;
            border-radius: 8px;
            cursor: pointer;

            &:active {
              opacity: 0.9;
            }
          }
        }
      }
    }

    .loading-more,
    .no-more {
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 20px;
      color: #999;
      font-size: 13px;

      .loading-icon {
        margin-right: 8px;
        animation: rotate 1s linear infinite;
      }
    }
  }
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>
